package com.mycode.interpreter16.resolve;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

// 指令处理类：工具类
public class InstructionHandler {

    private AbstractNode node;

    public void handle(String instruction) {
        AbstractNode left = null, right = null;
        AbstractNode direction = null, action = null, distance = null;
        Deque stack = new LinkedList();
        // Stack stack = new Stack();
        String[] words = instruction.split(" ");
        for (int i = 0; i < words.length; i++) {
            if (words[i].equalsIgnoreCase("and")) {
                // 弹出栈顶表达式作为左表达式
                left = (AbstractNode) stack.pop();
                String word1 = words[++i];
                direction = new DirectionNode(word1);
                String word2 = words[++i];
                action = new ActionNode(word2);
                String word3 = words[++i];
                distance = new DistanceNode(word3);
                // 右表达式
                right = new SentenceNode(direction, action, distance);
                // 将新表达式压入栈中
                stack.push(new AndNode(left, right));
            }
            else {
                String word1 = words[i];
                direction = new DirectionNode(word1);
                String word2 = words[++i];
                action = new ActionNode(word2);
                String word3 = words[++i];
                distance = new DistanceNode(word3);
                left = new SentenceNode(direction, action, distance);
                // 将新表达式压入栈中
                stack.push(left);
            }
        }
        // 将全部表达式从栈中弹出
        this.node = (AbstractNode) stack.pop();
    }

    public String output() {
        // 解释表达式
        String result = node.interpret();
        return result;
    }
}
